package com.greenantmall.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.avos.avoscloud.AVUser;
import com.greenantmall.R;
import com.greenantmall.adapter.GoodsListAdapterForImageItem;
import com.greenantmall.adapter.GoodsListAdapterForItem1;
import com.greenantmall.adapter.GoodsListAdapterForItem2;
import com.greenantmall.bean.ShoppingCart;
import com.greenantmall.bean.UIGoods;
import com.greenantmall.bean.UIGoodsList;
import com.greenantmall.service.RetrieveDataAsyn;
import com.greenantmall.service.RetrieveDataListener;
import com.greenantmall.utils.Const;
import com.greenantmall.utils.UtilTools;
import com.lsarah.utils.SystemBarTintManager;

public class GoodsListActivity extends BaseActivity 
	implements RetrieveDataListener, OnScrollListener, OnItemClickListener
{
	public static final String KEY_LIST_TYPE = "key_list_type";
	public static final int LIST_TYPE_FOR_HOME_PAGE_ITEM_1 = 1;
	public static final int LIST_TYPE_FOR_HOME_PAGE_ITEM_2 = 2;
	public static final int LIST_TYPE_FOR_HOME_PAGE_IMAGE_ITEM = 3;
	public static final int LIST_TYPE_FOR_HOME_PAGE_BANNERS = 4;
	
	public static final String KEY_GOODS_LIST = "key_goods_list";
	public static final String KEY_GOODS_RECOMMEND_OBJECT_ID = "key_goods_recommend_object_id";
	public static final String KEY_TITLE = "key_title";
	
	private int mCurrentListType = LIST_TYPE_FOR_HOME_PAGE_ITEM_1;
	private String mGoodsRecommendObjectId = "";
	
	private View mBackView;
	private View mBasketView;
	private TextView mBasketNumTv;
	private View mTabContainer;
	private TextView mTvTitle;
	private TextView mTvSalesVolume;
	private TextView mTvPrice;
	private TextView mTvNew;
	private GridView mGridView;
	private ProgressBar mProgressBar;
	private TextView mTvPrompt;
	
	private BaseAdapter mAdapter;
	private List<UIGoods> mDataList;
	private List<ShoppingCart> mShoppingCartList = new ArrayList<ShoppingCart>();
	
	private int mTotalCount = 0;
	private boolean isLoadingData = false;
	private int mCurrentOrderBy = 0;
	
	private OnClickListener mOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if(v.equals(mBackView)) {
				GoodsListActivity.this.finish();
			}
			else if(v.equals(mBasketView)) {
				if(AVUser.getCurrentUser() == null) {
					Intent intent = new Intent(GoodsListActivity.this, LoginActivity.class);
					startActivity(intent);
				}
				else {
					Intent intent = new Intent(GoodsListActivity.this, ShoppingCartActivity.class);
					startActivity(intent);
				}
			}
			else if(v.equals(mTvSalesVolume)) {
				mTvSalesVolume.setSelected(true);
				mTvPrice.setSelected(false);
				mTvNew.setSelected(false);
				mTvSalesVolume.setTextColor(getResources().getColor(R.color.green));
				mTvPrice.setTextColor(getResources().getColor(android.R.color.tab_indicator_text));
				mTvNew.setTextColor(getResources().getColor(android.R.color.tab_indicator_text));
				
				mCurrentOrderBy = 0;
				int start = 0;
		        int expectedCount = 30;
		        int requestId = start;
		        RetrieveDataAsyn.getInstance().getGoodsListByGoodsRecommendObjectId(
		        		mGoodsRecommendObjectId, mCurrentOrderBy, start, expectedCount, requestId, GoodsListActivity.this);
		        mProgressBar.setVisibility(View.VISIBLE);
		        mTvPrompt.setVisibility(View.GONE);
			}
			else if(v.equals(mTvPrice)) {
				mTvSalesVolume.setSelected(false);
				mTvPrice.setSelected(true);
				mTvNew.setSelected(false);
				mTvSalesVolume.setTextColor(getResources().getColor(android.R.color.tab_indicator_text));
				mTvPrice.setTextColor(getResources().getColor(R.color.green));
				mTvNew.setTextColor(getResources().getColor(android.R.color.tab_indicator_text));
				
				mCurrentOrderBy = 1;
				int start = 0;
		        int expectedCount = 30;
		        int requestId = start;
		        RetrieveDataAsyn.getInstance().getGoodsListByGoodsRecommendObjectId(
		        		mGoodsRecommendObjectId, mCurrentOrderBy, start, expectedCount, requestId, GoodsListActivity.this);
		        mProgressBar.setVisibility(View.VISIBLE);
		        mTvPrompt.setVisibility(View.GONE);
			}
			else if(v.equals(mTvNew)) {
				mTvSalesVolume.setSelected(false);
				mTvPrice.setSelected(false);
				mTvNew.setSelected(true);
				mTvSalesVolume.setTextColor(getResources().getColor(android.R.color.tab_indicator_text));
				mTvPrice.setTextColor(getResources().getColor(android.R.color.tab_indicator_text));
				mTvNew.setTextColor(getResources().getColor(R.color.green));
				
				mCurrentOrderBy = 2;
				int start = 0;
		        int expectedCount = 30;
		        int requestId = start;
		        RetrieveDataAsyn.getInstance().getGoodsListByGoodsRecommendObjectId(
		        		mGoodsRecommendObjectId, mCurrentOrderBy, start, expectedCount, requestId, GoodsListActivity.this);
		        mProgressBar.setVisibility(View.VISIBLE);
		        mTvPrompt.setVisibility(View.GONE);
			}
		}
	};
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(Const.SHOPPING_CART_CHANGED)) {
				refreshShoppingCartList();
			}
		}
	};
	
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        SystemBarTintManager.setContentView(this, R.layout.goods_list, getResources().getColor(R.color.green));
        mBackView = findViewById(R.id.goods_list_top_arrow_left);
        mBasketView = findViewById(R.id.goods_list_shop_basket);
		mBasketNumTv = (TextView)findViewById(R.id.goods_list_shop_basket_num);
        mTabContainer = findViewById(R.id.goods_list_tab_ll);
        mTvTitle = (TextView)findViewById(R.id.goods_list_top_des);
        mTvSalesVolume = (TextView)findViewById(R.id.goods_list_tv_sales_volume);
        mTvPrice = (TextView)findViewById(R.id.goods_list_tv_price);
        mTvNew = (TextView)findViewById(R.id.goods_list_tv_new);
        mGridView = (GridView)findViewById(R.id.goods_list_gridview);
        mProgressBar = (ProgressBar)findViewById(R.id.goods_list_prgressbar);
        mTvPrompt = (TextView)findViewById(R.id.goods_list_tv_prompt);
        
        mBackView.setOnClickListener(mOnClickListener);
        mBasketView.setOnClickListener(mOnClickListener);
        mTvSalesVolume.setOnClickListener(mOnClickListener);
        mTvPrice.setOnClickListener(mOnClickListener);
        mTvNew.setOnClickListener(mOnClickListener);
        mGridView.setOnScrollListener(this);
        mGridView.setOnItemClickListener(this);
        
        IntentFilter filter = new IntentFilter(Const.SHOPPING_CART_CHANGED);
        this.registerReceiver(mReceiver, filter);
        
        mDataList = new ArrayList<UIGoods>();
        retrieveData();
        
        refreshShoppingCartList();
    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	this.unregisterReceiver(mReceiver);
    }
    
    @SuppressWarnings("unchecked")
	private void retrieveData() {
    	// read title from intent
        String title = getIntent().getStringExtra(KEY_TITLE);
        if(!TextUtils.isEmpty(title)) {
        	mTvTitle.setText(title);
        }
    	
        // read list type from intent
    	mCurrentListType = getIntent().getIntExtra(KEY_LIST_TYPE, LIST_TYPE_FOR_HOME_PAGE_ITEM_1);
    	if(mCurrentListType == LIST_TYPE_FOR_HOME_PAGE_ITEM_1) {
    		// read ArrayList<UIGoods> from intent
            ArrayList<UIGoods> tempList = null;
            Serializable serializableData = getIntent().getSerializableExtra(KEY_GOODS_LIST);
            if(serializableData != null) {
            	tempList = (ArrayList<UIGoods>)serializableData;
            }
            Log.d("CEXX", "CEXX ---> GoodsListActivity ---> tempList : " + (tempList==null ? tempList : tempList.size()));
            
            mTabContainer.setVisibility(View.GONE);
        	mDataList.addAll(tempList);
        	mAdapter = new GoodsListAdapterForItem1(this, mDataList, mShoppingCartList);
            mGridView.setAdapter(mAdapter);
    	}
    	else if(mCurrentListType == LIST_TYPE_FOR_HOME_PAGE_ITEM_2) {
    		// read ArrayList<UIGoods> from intent
            ArrayList<UIGoods> tempList = null;
            Serializable serializableData = getIntent().getSerializableExtra(KEY_GOODS_LIST);
            if(serializableData != null) {
            	tempList = (ArrayList<UIGoods>)serializableData;
            }
            Log.d("CEXX", "CEXX ---> GoodsListActivity ---> tempList : " + (tempList==null ? tempList : tempList.size()));
            
            mTabContainer.setVisibility(View.GONE);
        	mDataList.addAll(tempList);
        	mAdapter = new GoodsListAdapterForItem2(this, mDataList, mShoppingCartList);
            mGridView.setAdapter(mAdapter);
    	}
    	else if(mCurrentListType == LIST_TYPE_FOR_HOME_PAGE_BANNERS) {
    		// read ArrayList<UIGoods> from intent
            ArrayList<UIGoods> tempList = null;
            Serializable serializableData = getIntent().getSerializableExtra(KEY_GOODS_LIST);
            if(serializableData != null) {
            	tempList = (ArrayList<UIGoods>)serializableData;
            }
            Log.d("CEXX", "CEXX ---> GoodsListActivity ---> tempList : " + (tempList==null ? tempList : tempList.size()));
            
            mTabContainer.setVisibility(View.GONE);
        	mDataList.addAll(tempList);
        	mAdapter = new GoodsListAdapterForImageItem(this, mDataList, mShoppingCartList);
            mGridView.setAdapter(mAdapter);
    	}
    	else if(mCurrentListType == LIST_TYPE_FOR_HOME_PAGE_IMAGE_ITEM) {
    		mAdapter = new GoodsListAdapterForImageItem(this, mDataList, mShoppingCartList);
            mGridView.setAdapter(mAdapter);
    		// read mGoodsRecommendObjectId from intent
    		mGoodsRecommendObjectId = getIntent().getStringExtra(KEY_GOODS_RECOMMEND_OBJECT_ID);
    		mTvSalesVolume.performClick();
    	}
    }
    
    private void refreshShoppingCartList() {
		mShoppingCartList.clear();
		
		List<ShoppingCart> scList = UtilTools.getShoppingCartDatas();
		if(scList != null) {
			mShoppingCartList.addAll(scList);
		}
		
		int size = mShoppingCartList.size();
		if(size == 0) {
			mBasketNumTv.setVisibility(View.GONE);
		}
		else {
			mBasketNumTv.setVisibility(View.VISIBLE);
			mBasketNumTv.setText(String.valueOf(size));
		}
		
		if(mAdapter != null) {
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void dataRetrieved(int requestId, Object data) {
		if(data != null) {
			UIGoodsList uiGoodsList = (UIGoodsList)data;
			
			if(requestId == 0) {
				mDataList.clear();
				mTotalCount = uiGoodsList.getTotalNum();
				mDataList.addAll(uiGoodsList.getUIGoodsList());
				mAdapter.notifyDataSetInvalidated();
			}
			else
			{
				mDataList.addAll(uiGoodsList.getUIGoodsList());
				mAdapter.notifyDataSetChanged();
			}
			
			isLoadingData = false;
			
			if(mDataList.size() == 0) {
				mProgressBar.setVisibility(View.GONE);
				mTvPrompt.setVisibility(View.VISIBLE);
				mTvPrompt.setText(R.string.goods_list_no_goods);
			}
			else{
				mProgressBar.setVisibility(View.GONE);
				mTvPrompt.setVisibility(View.GONE);
			}
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if(totalItemCount >= mTotalCount) {
			return;
		}
		
		if(isLoadingData) {
			return;
		}
		
		if(firstVisibleItem + visibleItemCount < totalItemCount) {
			return;
		}
		
		isLoadingData = true;
		int start = totalItemCount;
        int expectedCount = 18;
        int requestId = start;
        RetrieveDataAsyn.getInstance().getGoodsListByGoodsRecommendObjectId(
        		mGoodsRecommendObjectId, mCurrentOrderBy, start, expectedCount, requestId, GoodsListActivity.this);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Log.d("CEXX", "CEXX ---> GoodsListActivity ---> onItemClick ---> position : " + arg2);
//		UIGoods uiGoods = mDataList.get(arg2);
//		Intent intent = new Intent(this, DetailActivity.class);
//		intent.putExtra(DetailActivity.KEY_DETAIL_OBJECTID, uiGoods.getObjectId());
//		this.startActivity(intent); 
	}
}




